<meta charset="UTF-8">
<?php
require ('./lib/init.php');
// 判断是否登录
if (!acc()) {
    header('Location:login.php');
}
$art_id = $_GET['art_id'];
// 获取原来的分类
$sql = "select cat_id from art where art_id = '$art_id'";
$oldart = mGetRow($sql);
$oldcatid = $oldart['cat_id'];
//判断地址栏传来的 art_id 是否合法
if (!is_numeric($art_id)){
    error ('文章id不合法！','javascript:history.back(-1)');
}

//文章是否存在
$sql = "select * from art where art_id = $art_id";
if (!mGetrow($sql)){
    error('文章不存在','javascript:history.back(-1)');
}

//查询出所有栏目
$sql = "select * from cat";
$cats = mGetAll($sql);
if (empty($_POST)){
    $sql = "select title,content,cat_id,arttag,author from art where art_id = $art_id";
    $art = mGetRow($sql);
    include (ROOT . '/view/admin/artedit.html');
}else{
    //    检测标题是否为空
    $art['title'] = trim($_POST['title']);
    if ($art['title'] == ''){
        error('标题不能为空','javascript:history.back(-1)');
    }
//    检测栏目是否合法
    $art['cat_id']= $_POST['cat_id'];
    if (!is_numeric($art['cat_id'])){
        error('文章分类不合法！','javascript:history.back(-1)');
    }
//    检测内容是否为空
    $art['content'] = trim($_POST['content']);
    if ($art['content'] == ''){
        error('内容不能为空！','javascript:history.back(-1)');
    }
//    最后一次修改时间
    $art['lastup'] = time();
    if (!mExec('art',$art,'update'," art_id = $art_id ")){
            error('修改失败','javascript:history.back(-1)');
    }else{
        // 修改cat表中对应分类的文章的数量
        // 旧的文章分类文章数量-1
        $sql = "update cat set cat_num = cat_num - 1 where cat_id = '$oldcatid' ";
        mQuery($sql);
        // 新的文章分类文章数量+1
        $sql = "update cat set cat_num = cat_num +1 where cat_id = '$art[cat_id]'";
        mQuery($sql);
        //            删除原表中所有的tag
        $sql = "delete from tag where art_id = $art_id";
        if (mQuery($sql)){
            //        获取新的tag
            $tag = explode(',',$_POST['tag']);
            $sql = "insert into tag (art_id,tag) values  ";
            foreach ($tag as $v){
                $sql .= "(" . $art_id . ",' " . $v . "'),";
            }
            $sql = rtrim($sql,",");
            if (mQuery($sql)){
                $sql = "update art set arttag = '$_POST[tag]' where art_id = $art_id";
                if (mQuery($sql)){
                    succ ('修改成功！','artlist.php');
                }
                succ('修改成功！','artlist.php');
            }else{
                error ('文章内容修改成功，但是标签修改失败。','artlist.php');
            }
        }else{
            error ('文章内容修改成功，但是标签修改失败。','artlist.php');
        }

    }
}


?>
